package cookies.exercises;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-07-30
 * Time:3:10
 */
@WebServlet(name = "LoginServlet", urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        if (checkLogin(req)) {
            Cookie username = new Cookie("username", req.getParameter("username"));
            Cookie pwd = new Cookie("pwd", req.getParameter("pwd"));
            int expiry = 3 * 24 * 60 * 60;
            //expiry = 20;
            username.setMaxAge(expiry);
            pwd.setMaxAge(expiry);
            resp.addCookie(username);
            resp.addCookie(pwd);
            out.println("<h1>登录成功</h1>");
        } else {
            out.println("<h1>登录失败</h1>");
        }
        out.flush();
        out.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    private boolean checkLogin(HttpServletRequest req) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("pwd");
        if (username == null || password == null) {
            return false;
        }
        return username.equals("admin") && password.equals("123");
    }
}
